package com.kfm.filter;

import com.kfm.util.Contains;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

//@WebFilter("/*")
public class LoginFilter implements Filter {

    private List<String> excludePath = new ArrayList<>();
    private List<String> resourcesURL = new ArrayList<>();


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        ServletContext servletContext = filterConfig.getServletContext();

        String contextPath = servletContext.getContextPath();

        excludePath.add(contextPath + "/index.jsp"); // 登录页面
        excludePath.add(contextPath + "/login");// 处理登录的请求
        excludePath.add(contextPath + "/captcha");// 验证码的请求

        // 静态资源
        resourcesURL.add(".css");
        resourcesURL.add(".ico");
        resourcesURL.add(".jpg");
        resourcesURL.add(".png");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;

        String requestURI = httpServletRequest.getRequestURI();

        boolean next = false;

        // 排除 登录相关的路径
        if (excludePath.contains(requestURI)){
            next = true;
        } else {
            // 是否是静态资源
            // 获取请求的后缀, 也可以判断前缀  /static
            int index = requestURI.lastIndexOf(".");
            if (index >= 0){
                String suff = requestURI.substring(index);
                if (resourcesURL.contains(suff)){
                    next = true;
                }
            }
        }

        if (next){
            chain.doFilter(request, response);
        } else {
            // 判断登录
            HttpSession session = httpServletRequest.getSession();
            Object attribute = session.getAttribute(Contains.LOGIN_USER);
            if (attribute != null){
                chain.doFilter(request, response);
            } else {
                httpServletResponse.sendRedirect("index.jsp");
            }
        }

    }
}
